
var app = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        picPath: app.globalData.path,
        productId: '',
        indicatorDots: true,
        autoplay: true,
        interval: 3000,
        duration: 1000,
        current: 0,
        videos: [],
        loops: [],
        isMember: false, //是否为付费会员
        formats: [], //规格
        product_price: 0,
        product: {}, //商品信息
        format: {}, //当前选中的规格
        chooseNum: 1, //商品数量
        comments: [], // 评价
        commentNum: 2, // 评价个数
        answer_num: 1, // 问答个数
        answers: [],
        proPics: [], // 详情图数组
        noKucun: false,
        btnFlag: true, //返回顶部按钮显示
        parameterAlertShow: false, // 参数弹窗
        paras: [],
        productAlertShow: false, // 规格弹窗
        productAlertType: 0,
        collect: false,
        month_sales: 0, //月销量
    },

    openProductAlert: function (e) { //打开商品选择弹窗
        this.setData({
            productAlertType: e.currentTarget.dataset.type,
            productAlertShow: true,
            parameterAlertShow: false,
        })
    },
    closeHandle() {
        console.log(1);
        this.setData({
            productAlertShow: false
        })
    },
    closeProductAlert: function (e) { //关闭商品选择弹窗
        this.setData({
            productAlertShow: false,
        })
    },
    closeProductAlertSubmit() {
        if (this.data.productAlertType == 1) {
            this.addCart();
        } else {
            this.buyNow();
        }
    },
    //加入购物车
    addCart() {
        var num = this.data.chooseNum, that = this,
            url = app.globalData.url + "main/addCart",
            data = {
                shopId: app.globalData.shopId,
                userId: app.globalData.userId,
                productId: that.data.productId,
                productNum: num,
                formatId: that.data.format.formatId,
                productName: that.data.product.productName,
                formatImg: that.data.format.formatImg,
                formatPrice: that.data.format.formatPrice,
                formatSpecial: that.data.format.formatSpecial,
                formatName: that.data.format.formatName,
            },
            that = this;
        app.wxRequest(url, data, res => {
            console.log("加入购物车成功");
            if (res.flag) {
                wx.showToast({
                    title: '加入购物车成功',
                    icon: 'none', //图标，支持"success"、"loading"  
                })
                that.setData({
                    productAlertShow: false
                })
            } else {
                wx.showToast({
                    title: '加入购物车失败',
                    icon: 'none'
                })
            }
            console.log(res);
        }, err => { })
    },
    //立即购买
    buyNow() {
        var pro = this.data.product, format = this.data.format, pros = [];
        format.productNum = this.data.chooseNum
        pros.push(Object.assign(pro, format));
        console.log(pros);

        // return
        wx.navigateTo({
            url: '/packageProduct/pages/submitOrder/submitOrder?product=' + JSON.stringify(pros)
        })




    },
    changeFormart: function (e) { // 选择规格
        this.setData({
            format: e.currentTarget.dataset.item,
            productAlertShow: true
        })
    },
    openparameterAlert: function () { //打开参数弹窗
        this.setData({
            parameterAlertShow: true,
            productAlertShow: false,
        })
    },
    closeparameterAlert: function () { //关闭参数弹窗
        this.setData({
            parameterAlertShow: !this.data.parameterAlertShow
        })
    },
    toCart: function () {
        wx.navigateTo({
            url: '/packageProduct/pages/shoppingCart/shoppingCart',
        })
    },
    // 查看更多评价
    getMoreComment(e) {
        wx.navigateTo({
            url: '/packageProduct/pages/comments/comments?proid=' + e.currentTarget.dataset.proid,
        })
    },

    // 查看更多问答
    getMoreAnswer(e) {
        wx.navigateTo({
            url: '/packageProduct/pages/answer/answer?pro=' + JSON.stringify(e.currentTarget.dataset.pro),
        })
    },

    swipeChange: function (e) {
        this.setData({
            current: e.detail.current
        })
    },

    // 收藏
    toCollect(e) {
        var flag = e.currentTarget.dataset.flag
        wx.showLoading({
            title: '加载中',
        })
        var that = this;
        var url = app.globalData.url + "product/addCollectProduct",
            data = {
                userId: app.globalData.userId,
                productId: that.data.product.productId,
                flag,
            };
        app.wxRequest(url, data, res => {
            wx.hideLoading()
            if (res.flag) {
                console.log(res);
                that.setData({
                    collect: !that.data.collect
                })
                if (flag == 1) {
                    wx.showToast({
                        title: '收藏成功',
                        icon: 'none'
                    })
                } else if (flag == 0) {
                    wx.showToast({
                        title: '已取消',
                        icon: 'none'
                    })
                }
            } else {
                wx.showToast({
                    title: '操作失败，请重试',
                    icon: 'none'
                })
            }
        })
    },


    getMain() {
        wx.showLoading({ // 显示加载中loading效果 
            title: "加载中",
            mask: true //开启蒙版遮罩
        });
        var that = this, url = app.globalData.url + "product/listProDetail", loops = [], proPics = [], isSpecial = false, answers = [], answer_num = 0, comments = [], commentNum = 0, format = '', formarts = [], product = '', collect = false, month_sales = 0;
        app.wxRequest(url, {
            productId: that.data.productId,
            userId: app.globalData.userId
        }, res => {
            if (res.flag) {
                wx.hideLoading()
                var datas = res.data;
                console.log(datas);

                datas.bannerList.forEach(item => {
                    if (item.picFlag == 0) {
                        loops.push(item)
                    } else {
                        proPics.push(item)
                    }
                })
                datas.comments.forEach(item => {
                    item.imgError = false
                    item.errimg = '/img/avatar.png'
                })
                isSpecial = datas.product.productFlag == 1
                answers = datas.answerList
                answer_num = answers.length
                comments = datas.comments
                commentNum = comments.length
                formarts = datas.formatList
                format = formarts[0];
                product = datas.product
                collect = product.collectFlag == 1
                month_sales = product.productSales
                console.log(format);
                console.log(proPics);
                that.setData({
                    loops,
                    proPics,
                    isSpecial, answers, answer_num, comments, commentNum, format, formarts, product, collect, month_sales
                })

            }
        }, err => {
            console.log(err);
        })
    },


    imgErrHandle(e) {
        console.log(e);
        var index = e.currentTarget.dataset.index, list = this.data.comments;
        list[index].imgError = true
        this.setData({
            comments: list
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(options);
        this.setData({
            productId: options.id
        })
        if (options.userId) {
            var isLogin = wx.getStorageSync("isZhongHuiLogin"),
                that = this;
            if (!isLogin) {
                app.getInfo().then(function (res) {
                    console.log(res);
                    app.globalData.user = res.data.user
                    app.globalData.openId = res.data.openId
                    app.globalData.userId = res.data.user.userId
                    app.globalData.shopId = res.data.user.shopId || 0
                    wx.setStorageSync('isZhongHuiLogin', true)
                    wx.setStorageSync('user', JSON.stringify(res.data.user))
                    that.getMain()
                    if (res.data.user.userName == null) {
                        wx.showModal({
                            title: '提示',
                            content: '请完善您的信息',
                            cancelText: '先逛逛',
                            confirmText: '立即完善',
                            complete: (res) => {
                                if (res.cancel) {
                                }
                                if (res.confirm) {
                                    wx.navigateTo({
                                        url: '/packageUser/pages/userInfo/userInfo',
                                    })
                                }
                            }
                        })
                    }
                })
            } else {
                var user = JSON.parse(wx.getStorageSync('user'))
                if (user.userName == null) {
                    wx.showModal({
                        title: '提示',
                        content: '请完善您的信息',
                        cancelText: '再等等',
                        confirmText: '立即完善',
                        complete: (res) => {
                            if (res.cancel) {
                            }
                            if (res.confirm) {
                                wx.navigateTo({
                                    url: '/packageUser/pages/userInfo/userInfo',
                                })
                            }
                        }
                    })
                }
                that.getMain()
            }
        } else {
            this.getMain()

        }

    },

    //加
    addProductNum() {
        if (this.data.product.productFlag == 1) {
            wx.showToast({
                title: '特殊商品不可更改数量',
                icon: 'none'
            })
            return
        }
        if (this.data.chooseNum >= this.data.format.formatInventory) {
            return;
        } else {
            var num = this.data.chooseNum + 1;
            this.setData({
                chooseNum: num,
            })
        }
    },
    //减
    subProductNum() {
        console.log(this.data.product);

        if (this.data.product.productFlag == 1) {
            wx.showToast({
                title: '特殊商品不可更改数量',
                icon: 'none'
            })
            return
        }

        if (this.data.chooseNum <= 1) {
            return;
        } else {
            var num = this.data.chooseNum - 1;
            this.setData({
                chooseNum: num,
                productAlertShow: true
            })
            console.log(this.data.productAlertShow);
        }
    },
    // shareImg(){
    //   console.log("近日分享了");
    //   wx.updateShareMenu({
    //     withShareTicket: true,
    //     success(res){
    //       console.log(res);
    //     }
    //   })
    // },
    // toShare(){
    //   console.log("近日分享了5656");
    //   wx.showShareMenu({

    //     withShareTicket:true,

    //     menus:['shareAppMessage','shareTimeline']
    //   })
    // },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        var that = this;
        return {
            title: that.data.product.productName,
            imageUrl: `${that.data.picPath}zhonghui/product/${that.data.product.productPic}`,
            path: '/packageProduct/pages/productDetail/productDetail?scene=' + app.globalData.userId + '&id=' + that.data.productId
        }
    }
})